<template>
  <k-form-modal
    drawer
    :title="`${isEdit ? '更新' : '新增'}订单`"
    label-width="80px"
    v-bind="formModalState"
    width="649px"
    :confirm-disabled="!hasPermission(AuthCode.KGJ_ORDER_UPDATE, false)"
    v-on="formModalEvent"
  >
    <el-form-item label="用户id" prop="user_id" :rules="[{ required: true, message: '请输入昵称、手机号' }]">
      <el-input v-model="state.model.user_id" :disabled="isEdit" placeholder="请输入用户昵称、手机号" />
    </el-form-item>
    <el-form-item label="付款金额" prop="total_fee" :rules="[{ required: true, message: '请输入付款金额' }]">
      <el-input-number v-model="state.model.total_fee" style="width: 220px" controls-position="right" placeholder="请输入付款金额" />
    </el-form-item>
    <el-form-item label="付款时间" prop="pay_time" :rules="[{ required: true, message: '请选择付款时间' }]">
      <el-date-picker v-model="state.model.pay_time" type="datetime" placeholder="请选择付款时间" :shortcuts="dateShortcuts" />
    </el-form-item>
    <el-form-item label="产品类型" prop="product_type">
      <el-radio-group v-model="state.model.product_type" :disabled="isEdit" @change="handleRedjust">
        <el-radio v-for="item in productTypeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="会员类型" prop="level">
      <el-radio-group v-model="state.model.level" :disabled="isEdit" @change="handleRedjust">
        <el-radio v-for="item in levelOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="购买类型" prop="month">
      <el-radio-group v-model="state.model.month" :disabled="isEdit">
        <template v-for="item in monthOptions" :key="item.value">
          <el-radio v-if="item.value === 7 ? state.model.level === 20 && state.model.product_type === 1 : true" :label="item.value">{{ item.label }}</el-radio>
        </template>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="团队人数" prop="slave_count">
      <el-radio-group v-model="state.model.slave_count" :disabled="slaveCountDisabled">
        <el-radio
          v-for="item in newGroupMemberCountOptions"
          :key="item.value"
          :disabled="state.model.product_type === 3 && ((state.model.level === 30 && item.value === 1) || (state.model.level === 20 && item.value === 1))"
          :label="item.value"
        >{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="优惠类型" prop="discount_type">
      <el-checkbox-group v-model="state.model.discount_type" :disabled="isEdit">
        <el-checkbox v-for="item in discountTypeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item label="备注" prop="remark" :rules="[{ required: true, message: '请输入备注' }]">
      <el-input v-model="state.model.remark" placeholder="请输入备注" type="textarea" :rows="4" />
    </el-form-item>
    <el-form-item label="销售" prop="sales_id">
      <el-select-v2 v-model="state.model.sales_id" :disabled="isEdit" placeholder="不限" :options="salesList"> </el-select-v2>
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useFormModal, baseAlert } from '@crud/index';
import { getSalesUserList } from '@/api/crm-kgj/sales';
import { getOrderDetail, createOrder, updateOrder } from '@/api/crm-kgj/order';
import { productTypeOptions, levelOptions, discountTypeOptions } from '../hooks/use-table';
import { SupremeTeamCountOptions, OtherTeamCountOptions } from '@/constants';
import dayjs from 'dayjs';
import { hasPermission, AuthCode } from '@/modules/auth';
import { toolGetSingleDateShortCuts as dateShortcuts } from '@/utils';

defineOptions({ name: 'MajorCustomerEditModal' });

const formRef = ref();
const emits = defineEmits(['after-submit']);
const isEdit = ref(false);
const salesList = ref([{ label: '不限', value: '' }]);
const slaveCountDisabled = ref(false);
const newGroupMemberCountOptions = computed(() => (state.model.level <= 20 ? OtherTeamCountOptions : SupremeTeamCountOptions));
const monthOptions = computed(() => {
  let arr = [];
  if (state.model.level === 20 && state.model.product_type === 1) {
    arr.push({ label: '一周', value: 7 });
  }
  if (state.model.level < 30) {
    arr.push({ label: '一月', value: 1 });
  }
  arr = [...arr, { label: '一季', value: 3 }, { label: '一年', value: 12 }];
  return arr;
});
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    remark: null,
    // user_id: '',
    product_type: 1,
    level: 30,
    month: 3,
    slave_count: 1
  },
  getParams: (model) => model,
  onShow: async (mode = 0, data: any) => {
    isEdit.value = !!mode;
    getSalesList();
    if (mode === 0) {
      methods.resetModel();
    } else if (data) {
      const { trade_no: no } = data;
      state.contentLoading = true;
      const res = await getOrderDetail({ no });
      state.contentLoading = false;
      if (!res.err) {
        state.model = { ...res.data, pay_time: dayjs(res.data.pay_time * 1000).valueOf(), slave_count: res.data.term_count, term_count: undefined };
      }
    }
  },
  onSubmit: async (model, mode = 0) => {
    if (model.trade_type !== 4 && mode > 0) {
      baseAlert({ title: '错误提示', message: '非对公转账的订单不能编辑' });
      return;
    }
    model = { ...model, pay_time: dayjs(model.pay_time).unix().valueOf() };
    const res = await (isEdit.value ? updateOrder(model) : createOrder(model));
    if (!res.err) {
      ElMessage.success('保存成功');
      emits('after-submit');
    }
    return res;
  }
});
/** 获取销售列表 */
const handleSalesUserList = async () => {
  const res = await getSalesUserList({ data: {}, params: { page: 1, limit: 500 } });
  if (res.err) return;
  salesList.value = salesList.value.concat(res.data?.items?.map((item) => ({ label: item.sales_name, value: item.sales_id })));
};

/** 重新校验逻辑并赋值 */
const handleRedjust = () => {
  /**
   * 如果是购买
   * 至尊版：默认选中1人 旗舰版：默认选中1人
   * 如果是扩充
   * 至尊版：默认选中3人  旗舰版：默认选中3人
   * 低于旗舰版都为1人
   **/
  state.model.slave_count = state.model.level >= 20 ? (state.model.product_type === 3 ? 3 : 1) : 1;

  slaveCountDisabled.value = isEdit.value || ![20, 30].includes(state.model.level) || (state.model.product_type === 3 && ![20, 30].includes(state.model.level));
  state.model.month = state.model.level > 20 ? 3 : 1;
};

const getSalesList = () => {
  /** 查看销售列表authCode: 3001 */
  if (hasPermission(AuthCode.KGJ_SALES_LIST, false)) {
    handleSalesUserList();
  }
};
defineExpose({
  show: methods.show
});
</script>
